<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/26
 * Time: 9:50
 */

namespace backend\controllers;


use backend\models\Product;
use common\models\Category;
use yii\data\Pagination;
use yii\web\Controller;
use yii\web\UploadedFile;

class ProductController extends Controller
{
   public function actionIndex()
   {
       $model = Product::find();
       $count = $model->count();
       $page = new Pagination(['totalCount'=>$count,'pageSize'=>5]);
       $products = $model->offset($page->offset)->limit($page->limit)->all();
//       print_r($products);
//       die;
       return $this->render('index',['products'=>$products,'pager'=>$page]);
   }
   public function actionAdd()
   {

       $model = new Product();
       $cates = new Category();
       $opt = $cates->getOption();
        if (\Yii::$app->request->isPost)
        {
            $post = \Yii::$app->request->post();
            $model->load($post);
            $model->pics = UploadedFile::getInstances($model,'pics');
            $model->cover = UploadedFile::getInstance($model,'cover');
            $pics= $model->upload();
            if($pics)
            {
                $model->cover = $pics['cover'];
                $model->pics = $pics['pics'];
                if($model->save()){
                    \Yii::$app->session->setFlash('info','添加成功');
                }

            }else{
                $model->addError('cover','封面不能为空');
            }
        }
       return $this->render('add',['model'=>$model,'opts'=>$opt]);
   }
   public function actionEdit()
   {
       $id = \Yii::$app->request->get('id');
       $model = Product::findOne($id);
       $cates = new Category();
       $opt = $cates->getOption();
       if(\Yii::$app->request->isPost)
       {

       }
      return $this->render('add',['model'=>$model,'opts'=>$opt]);
   }
   public function actionRemovepic()
   {
       $id = \Yii::$app->request->get('id');
       $key = \Yii::$app->request->get('key');
       $product = Product::findOne($id);
        $path = json_decode($product->pics);
       unlink($path[$key]);
       unset($path[$key]);
        Product::updateAll(['pics'=>json_encode($path)],"productid={$id}");
        return $this->redirect(['product/edit','id'=>$id]);
   }

}